﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;

namespace Admin.NET.Application;

/// <summary>
/// 销售退货服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class SalesreturnsService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Salesreturns> _salesreturnsRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public SalesreturnsService(SqlSugarRepository<Salesreturns> salesreturnsRep, ISqlSugarClient sqlSugarClient)
    {
        _salesreturnsRep = salesreturnsRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询销售退货 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询销售退货")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<SalesreturnsOutput>> Page(PageSalesreturnsInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _salesreturnsRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.ReturnOrderNumber.Contains(input.Keyword) || u.BillNumber.Contains(input.Keyword) || u.Contact.Contains(input.Keyword) || u.Contacts.Contains(input.Keyword) || u.HeadOfSales.Contains(input.Keyword) || u.ReturnedItems.Contains(input.Keyword) || u.MakeASingle.Contains(input.Keyword) || u.Reviewers.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ReturnOrderNumber), u => u.ReturnOrderNumber.Contains(input.ReturnOrderNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.BillNumber), u => u.BillNumber.Contains(input.BillNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Contact), u => u.Contact.Contains(input.Contact.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Contacts), u => u.Contacts.Contains(input.Contacts.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.HeadOfSales), u => u.HeadOfSales.Contains(input.HeadOfSales.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ReturnedItems), u => u.ReturnedItems.Contains(input.ReturnedItems.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.MakeASingle), u => u.MakeASingle.Contains(input.MakeASingle.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Reviewers), u => u.Reviewers.Contains(input.Reviewers.Trim()))
            .WhereIF(input.DocumentStatus != null, u => u.DocumentStatus == input.DocumentStatus)
            .WhereIF(input.ReturnDateRange?.Length == 2, u => u.ReturnDate >= input.ReturnDateRange[0] && u.ReturnDate <= input.ReturnDateRange[1])
            .WhereIF(input.ClientNameId != null, u => u.ClientNameId == input.ClientNameId)
            .WhereIF(input.SalesDepartmentId != null, u => u.SalesDepartmentId == input.SalesDepartmentId)
            .WhereIF(input.NumberOfReturns != null, u => u.NumberOfReturns == input.NumberOfReturns)
            .WhereIF(input.DepartmentId != null, u => u.DepartmentId == input.DepartmentId)
            .WhereIF(input.MakeASingleDateRange?.Length == 2, u => u.MakeASingleDate >= input.MakeASingleDateRange[0] && u.MakeASingleDate <= input.MakeASingleDateRange[1])
            .WhereIF(input.ReviewTimeRange?.Length == 2, u => u.ReviewTime >= input.ReviewTimeRange[0] && u.ReviewTime <= input.ReviewTimeRange[1])
            .LeftJoin<Customermanagement>((u, clientName) => u.ClientNameId == clientName.Id)
            .LeftJoin<PostManagement>((u, clientName, salesDepartment) => u.SalesDepartmentId == salesDepartment.Id)
            .LeftJoin<Organization>((u, clientName, salesDepartment, department) => u.DepartmentId == department.Id)
            .Select((u, clientName, salesDepartment, department) => new SalesreturnsOutput
            {
                Id = u.Id,
                ReturnOrderNumber = u.ReturnOrderNumber,
                DocumentStatus = u.DocumentStatus,
                ReturnDate = u.ReturnDate,
                BillNumber = u.BillNumber,
                ClientNameId = u.ClientNameId,
                ClientNameFkDisplayName = $"{clientName.CustomerName}",
                Contact = u.Contact,
                Contacts = u.Contacts,
                SalesDepartmentId = u.SalesDepartmentId,
                SalesDepartmentFkDisplayName = $"{salesDepartment.PostName}",
                HeadOfSales = u.HeadOfSales,
                NumberOfReturns = u.NumberOfReturns,
                ReturnMoney = u.ReturnMoney,
                ReturnedItems = u.ReturnedItems,
                MakeASingle = u.MakeASingle,
                DepartmentId = u.DepartmentId,
                DepartmentFkDisplayName = $"{department.OrganizationName}",
                MakeASingleDate = u.MakeASingleDate,
                Reviewers = u.Reviewers,
                ReviewTime = u.ReviewTime,
                IsDelete = u.IsDelete,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取销售退货详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取销售退货详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Salesreturns> Detail([FromQuery] QueryByIdSalesreturnsInput input)
    {
        return await _salesreturnsRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加销售退货 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加销售退货")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddSalesreturnsInput input)
    {
        var entity = input.Adapt<Salesreturns>();
        return await _salesreturnsRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新销售退货 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新销售退货")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateSalesreturnsInput input)
    {
        var entity = input.Adapt<Salesreturns>();
        await _salesreturnsRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除销售退货 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除销售退货")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteSalesreturnsInput input)
    {
        var entity = await _salesreturnsRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _salesreturnsRep.FakeDeleteAsync(entity);   //假删除
        //await _salesreturnsRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除销售退货 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除销售退货")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteSalesreturnsInput> input)
    {
        var exp = Expressionable.Create<Salesreturns>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _salesreturnsRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _salesreturnsRep.FakeDeleteAsync(list);   //假删除
        //return await _salesreturnsRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataSalesreturnsInput input)
    {
        var clientNameIdData = await _salesreturnsRep.Context.Queryable<Customermanagement>()
            .InnerJoinIF<Salesreturns>(input.FromPage, (u, r) => u.Id == r.ClientNameId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.CustomerName}"
            }).ToListAsync();
        var salesDepartmentIdData = await _salesreturnsRep.Context.Queryable<PostManagement>()
            .InnerJoinIF<Salesreturns>(input.FromPage, (u, r) => u.Id == r.SalesDepartmentId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.PostName}"
            }).ToListAsync();
        var departmentIdData = await _salesreturnsRep.Context.Queryable<Organization>()
            .InnerJoinIF<Salesreturns>(input.FromPage, (u, r) => u.Id == r.DepartmentId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.OrganizationName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "clientNameId", clientNameIdData },
            { "salesDepartmentId", salesDepartmentIdData },
            { "departmentId", departmentIdData },
        };
    }
    
    /// <summary>
    /// 导出销售退货记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出销售退货记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageSalesreturnsInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportSalesreturnsOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "销售退货导出记录");
    }
    
    /// <summary>
    /// 下载销售退货数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载销售退货数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportSalesreturnsOutput>(), "销售退货导入模板", (_, info) =>
        {
            if (nameof(ExportSalesreturnsOutput.ClientNameFkDisplayName) == info.Name) return _salesreturnsRep.Context.Queryable<Customermanagement>().Select(u => $"{u.CustomerName}").Distinct().ToList();
            if (nameof(ExportSalesreturnsOutput.SalesDepartmentFkDisplayName) == info.Name) return _salesreturnsRep.Context.Queryable<PostManagement>().Select(u => $"{u.PostName}").Distinct().ToList();
            if (nameof(ExportSalesreturnsOutput.DepartmentFkDisplayName) == info.Name) return _salesreturnsRep.Context.Queryable<TreeParentOutput>().Select(u => $"{u.OrganizationName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入销售退货记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入销售退货记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportSalesreturnsInput, Salesreturns>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 客户名称
                    var clientNameIdLabelList = pageItems.Where(x => x.ClientNameFkDisplayName != null).Select(x => x.ClientNameFkDisplayName).Distinct().ToList();
                    if (clientNameIdLabelList.Any()) {
                        var clientNameIdLinkMap = _salesreturnsRep.Context.Queryable<Customermanagement>().Where(u => clientNameIdLabelList.Contains($"{u.CustomerName}")).ToList().ToDictionary(u => $"{u.CustomerName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.ClientNameId = clientNameIdLinkMap.GetValueOrDefault(e.ClientNameFkDisplayName ?? "");
                            if (e.ClientNameId == null) e.Error = "客户名称链接失败";
                        });
                    }
                    // 链接 销售部门
                    var salesDepartmentIdLabelList = pageItems.Where(x => x.SalesDepartmentFkDisplayName != null).Select(x => x.SalesDepartmentFkDisplayName).Distinct().ToList();
                    if (salesDepartmentIdLabelList.Any()) {
                        var salesDepartmentIdLinkMap = _salesreturnsRep.Context.Queryable<PostManagement>().Where(u => salesDepartmentIdLabelList.Contains($"{u.PostName}")).ToList().ToDictionary(u => $"{u.PostName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.SalesDepartmentId = salesDepartmentIdLinkMap.GetValueOrDefault(e.SalesDepartmentFkDisplayName ?? "");
                            if (e.SalesDepartmentId == null) e.Error = "销售部门链接失败";
                        });
                    }
                    // 链接 所在部门
                    var departmentIdLabelList = pageItems.Where(x => x.DepartmentFkDisplayName != null).Select(x => x.DepartmentFkDisplayName).Distinct().ToList();
                    if (departmentIdLabelList.Any()) {
                        var departmentIdLinkMap = _salesreturnsRep.Context.Queryable<Organization>().Where(u => departmentIdLabelList.Contains($"{u.OrganizationName}")).ToList().ToDictionary(u => $"{u.OrganizationName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.DepartmentId = departmentIdLinkMap.GetValueOrDefault(e.DepartmentFkDisplayName ?? "");
                            if (e.DepartmentId == null) e.Error = "所在部门链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Salesreturns>>();
                    
                    var storageable = _salesreturnsRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.ReturnOrderNumber?.Length > 32, "退货单号长度不能超过32个字符")
                        .SplitError(it => it.Item.BillNumber?.Length > 32, "销售单号长度不能超过32个字符")
                        .SplitError(it => it.Item.Contact?.Length > 32, "联系人长度不能超过32个字符")
                        .SplitError(it => it.Item.Contacts?.Length > 32, "联系方式长度不能超过32个字符")
                        .SplitError(it => it.Item.HeadOfSales?.Length > 32, "销售负责人长度不能超过32个字符")
                        .SplitError(it => it.Item.ReturnedItems?.Length > 32, "退货货品长度不能超过32个字符")
                        .SplitError(it => it.Item.MakeASingle?.Length > 32, "制单人长度不能超过32个字符")
                        .SplitError(it => it.Item.Reviewers?.Length > 32, "审核人长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
